import { modelService } from "@/modules/model/service";
import { propertyUtil } from "../PropertyUtil";
import { PropertyRow } from "../types";
import { PaneModel } from "./PaneModel";
export type BehaviorTable = {
  isExpand: boolean;
  isEdit: boolean;
  isSelect: boolean;
  rowId: string;
  rowIndex?: number;
  rowType: BehaviorType | string;
  name: string;
  children?: BehaviorValue[];
};
export enum BehaviorType {
  ClassifierBehavior = "classifierBehavior",
  OwnedBehaviors = "ownedBehaviors",
  AllocatedBehaviors = "allocatedBehaviors",
  InheritedBehaviors = "inheritedBehaviors"
}

export type BehaviorValue = {
  id: string;

  visible: boolean;
  isSelect?: boolean;
  isEdit: boolean;
  readonly: boolean;
  rowType: BehaviorType | string;
  name: any;
  type: any;
  owner: any;
  valueSpecification: any;
  icon?: string;
  children?: any[];
};
export type BehaviorData = {
  classifierBehavior: Behaviors[];
  allocatedBehaviors: Behaviors[];
  ownedBehaviors: Behaviors[];
  inheritedBehaviors: Behaviors[];
};
export type Behaviors = {
  name: string;
  icon: string;
  instanceId: string;
  cells: Cells[];
};
export interface Cells extends PropertyRow {
  isEdite: boolean;
}
export type BehaviroSpanMethodProps = {
  row: BehaviorValue;
  column: any;
  rowIndex: number;
  columnIndex: number;
};
export type ColumnValue = {
  name: string;
  icon?: string;
  qualifiedeName?: string;
};

export type CreateBehaviorOptions = {
  cnName: string;
  enName: string;
  label: string;
  metaclass: string;
  value: string;
  icon: string;
};
export class BehaviorsPaneModel extends PaneModel {
  options: CreateBehaviorOptions[] = [
    {
      enName: "State Machine",
      cnName: "状态机",
      label: "状态机",
      metaclass: "StateMachine",
      value: "StateMachine",
      icon: "statics/images/sysml/StateMachine.svg"
    },
    {
      enName: "Activity",
      cnName: "活动",
      label: "活动",
      metaclass: "Activity",
      value: "Activity",
      icon: "statics/images/sysml/Activity.svg"
    },
    {
      enName: "Interaction",
      cnName: "交互",
      label: "交互",
      metaclass: "Interaction",
      value: "Interaction",
      icon: "statics/images/sysml/Interaction.svg"
    },
    {
      enName: "opaque behavior",
      cnName: "不透明行为",
      label: "不透明行为",
      metaclass: "OpaqueBehavior",
      value: "OpaqueBehavior",
      icon: "statics/images/sysml/OpaqueBehavior.svg"
    }
  ];
  tableData: BehaviorValue[] = [];
  tableHeader: [] = [];
  loading = false;
  editName: string | undefined = "";
  editInstanceId: string | undefined = "";
  behaviorsType = {
    classifierBehavior: "分类行为",
    ownedBehaviors: "拥有的行为",
    allocatedBehaviors: "分配的行为",
    InheritedBehaviors: "继承的行为"
  };
  selectedRow: any = ""; // 选中的行
  selectedCell: any = ""; // 选中的cell
  selectedBehaviorId = ""; // 选中的行的行为id
  expandRowKeys = [
    BehaviorType.ClassifierBehavior,
    BehaviorType.AllocatedBehaviors,
    BehaviorType.InheritedBehaviors,
    BehaviorType.OwnedBehaviors
  ]; // 展开行id
  /*
   *新建选项
   */

  handelSpread() {
    this.expandRowKeys = [
      BehaviorType.ClassifierBehavior,
      BehaviorType.AllocatedBehaviors,
      BehaviorType.InheritedBehaviors,
      BehaviorType.OwnedBehaviors
    ];
  }
  handleShrink() {
    this.expandRowKeys = [];
  }

  async handleCreateBehavior(metaclass: string) {
    await modelService.addModel(this.tabsModel.data.projectId!, this.tabsModel.data.modelId!, metaclass);
    this.fresh();
  }
  async handleApplyClassfireBehavior() {
    const { projectId, modelId } = this.tabsModel.data;
    // console.log(modelId, 'modelId', this.selectedBehaviorId);

    if (!projectId || !modelId) return;
    const row: any = {
      addMethod: "",
      dataType: "Instance",
      modelId: modelId,
      instanceId: modelId,
      isMultiplicity: false,
      key: "BehavioredClassifier-classifierBehavior",
      projectId: projectId,
      updateMethod: "",
      value: this.selectedRow.id
    };
    await propertyUtil.updatePropertyAndFresh(row, this.selectedBehaviorId, true);

    this.fresh();
  }
  async handleCreateOperation() {
    // console.log('handleCreateOperation', this.selectedRow.id);

    if (!this.selectedRow || !this.selectedRow.id) return;
    await modelService.createOperationAndApply(this.tabsModel.data.projectId!, this.selectedRow.id);
    await this.fresh();
  }
  async loadTable() {
    const { projectId, modelId } = this.tabsModel.data;

    if (!projectId || !modelId) {
      this.tableData = [];
      return this.tableData;
    }
    let res: BehaviorData = await modelService.queryBehavior(this.tabsModel.data.projectId!, this.tabsModel.data.modelId!);
    this.tableData = [];
    // console.log(res.classifierBehavior[0], 'b0');
    Object.keys(res).forEach(item => {
      this.formatTableData(res[item], item);
    });
    // console.log(this.tableData, '行为分组');
  }

  async loadDataWhenNotLoad(): Promise<void> {
    if (!this.loaded) {
      await this.loadTable();
    }
  }
  formatTableData(data: Behaviors[], key: string) {
    if (key) {
      key = key[0].toLocaleUpperCase() + key.substring(1);
    }
    // console.log(data, key, 'datares');

    if (!data || data.length == 0 || !data[0] || data[0].cells.length == 0) return;
    let children: BehaviorValue[] = [];

    data.forEach(element => {
      element.cells.forEach(cell => {
        cell.modelId = element.instanceId;
        cell.isEdite = false;
      });

      const child: BehaviorValue = {
        id: element.instanceId,

        name: element.cells[0],
        type: { name: element.cells[1].value, icon: element.icon, isEdite: false, readonly: true },
        owner: element.cells[2],
        valueSpecification: element.cells[3],
        isEdit: false,
        readonly: false,
        rowType: BehaviorType[key],
        visible: true
      };
      children.push(child);
    });
    let behaviorTableData: BehaviorValue = {
      id: BehaviorType[key],
      name: { name: this.behaviorsType[BehaviorType[key]], icon: "statics/images/sysml/Block.svg", isEdite: false, readonly: true },
      type: {},
      owner: {},
      rowType: BehaviorType[key],
      valueSpecification: {},
      visible: true,
      isEdit: false,
      readonly: true,
      children: children
    };
    this.tableData.push(behaviorTableData);
  }
  handelEdit() {
    // 更新所有cell的编辑状态为false
    this.tableData.forEach((item: BehaviorValue) => {
      if (item.children) {
        item.children.forEach((child: BehaviorValue) => {
          child.name.isEdite = false;
          child.type.isEdite = false;
          child.owner.isEdite = false;
          child.valueSpecification.isEdite = false;
        });
      }
    });
    // 查找对应cell的isEdite，改成true
    this.tableData.forEach((item: BehaviorValue) => {
      if (item.children) {
        item.children.forEach((child: BehaviorValue) => {
          if (child.id == this.selectedRow.id) {
            if (child[this.selectedCell.property]) {
              child[this.selectedCell.property].isEdite = true;
            }
          }
        });
      }
    });
  }

  async handleRename() {
    if (!this.tabsModel.data.projectId || !this.tabsModel.data.modelId || !this.editInstanceId) return;
    await modelService.renameNode(this.tabsModel.data.projectId!, this.editInstanceId, this.editName!);
    await this.fresh();
  }
  async handleDelete() {
    if (!this.selectedRow) return;
    await modelService.removeModel(this.tabsModel.data.projectId!, [this.selectedRow.id]);
    this.selectedRow.value = "";
    await this.fresh();
  }
  async fresh() {
    this.loadTable();
  }

  async clear() {
    this.tableData = [];
    this.loaded = false;
  }
}
